<?php
namespace Admin\Api;

use Admin\Common\Controller;
use Portal\Domain\Admin as AdminDomain;

class Site extends Controller {

    // 取消登录
    protected $isNeedLogin = false;

    /**
     * 后台首页
     */
    public function index() {
        $this->doUserCheck();
        
        return $this->render('site/index.html');
    }

    /**
     * 退出
     */
    public function login() {
        $username = $this->request->get('username', '');
        $password = $this->request->get('password', '');

        if (\PhalApi\DI()->admin->check(false)) {
            header('Location: /admin/');
            exit();
        }

        $isLogin = false;
        $error = null;
        if ($password && $username) {
            $isLogin = \PhalApi\DI()->iadminosOAuth->login($username, $password, $error);
            if ($isLogin) {
                header('Location: /admin/');
                exit();
            }
        }

        $data = array('username' => $username, 'password' => $password, 'error' => $error);

        return $this->render('site/login.html', $data, false);
    }

    /**
    protected function loginOAuth($username, $password, &$errorMsg = '') {
        $provider = new \League\OAuth2\Client\Provider\GenericProvider(\PhalApi\DI()->config->get('admin.oauth'));

        try {

            // Try to get an access token using the resource owner password credentials grant.
            $accessToken = $provider->getAccessToken('password', [
                'username' => $username,
                'password' => $password
            ]);

        } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

            // Failed to get the access token
            //exit($e->getMessage());

            $errorMsg = $e->getMessage();
            return false;
        }

        return true;
    }
    **/

    /**
     * 退出管理员登录
     * @desc 退出当前管理的登录
     */
    public function logout() {
        \PhalApi\DI()->admin->logout();
        header('Location: /admin/');
        exit();
    }

    public function test() {
        return $this->render('site/test.html', array('name' => 'iAdminOS'));
    }
}
